
import { observable, action } from 'mobx';
import { ListStore } from './listStore'
import { WeaTools,WeaLocaleProvider } from 'ecCom';
import * as API_LIST from '../apis/list';
import * as _ from 'lodash';
import * as API_SUPERVISE from '../apis/supervise';
import {message} from 'antd';
const getLabel = WeaLocaleProvider.getLabel;
const Base64 = WeaTools.Base64
/**
 * @author liuzy 2017-10-24
 * 待办/已办/我的请求共用的store
 */
export class ReqListStore extends ListStore{

    baseParams = {
        method: "all",
        offical: "",
        officalType: -1,
        hideNoDataTab:false
    };
    urlParams = {};
    topTabTemp = [];
    searchParams = {
        viewcondition:0,
        defaultTabVal:-1
    };
    quickSearchParams = {};
    fromQuickSearch = false;
    sharearg = {};

    nowViewType = 2;

    @observable showBatchSupervisor = false;
    _singleRequestid = '';

    //短信
    @observable smsVisible = false;
    @observable smsVisible_mount = false;//控制短信组件是否加载
    @observable smsParams = {src:'supervise',requestid:-1};

    //邮件
    @observable emailVisible = false;
    @observable emailVisible_mount = false;//控制邮件组件是否加载
    @observable fwquery = {};

    constructor(){
        super();
        this.appendBaseParams = this.appendBaseParams.bind(this);
        this.initDatas = this.initDatas.bind(this);
        this.doSearch = this.doSearch.bind(this);
        this.setConditionByTree = this.setConditionByTree.bind(this);
        this.clearStatus = this.clearStatus.bind(this);
        this.reLoad = this.reLoad.bind(this);
        this.doSupervise = this.doSupervise.bind(this);
        this.setShowBatchSupervisor = this.setShowBatchSupervisor.bind(this);
        this.setShowBatchSupervisorEmail = this.setShowBatchSupervisorEmail.bind(this);
        this.setShowBatchSupervisorSms = this.setShowBatchSupervisorSms.bind(this);
        this.setSmsVisible = this.setSmsVisible.bind(this);
        this.setSmsParams = this.setSmsParams.bind(this);
        this.setEmailVisible = this.setEmailVisible.bind(this);
        this.getSendEmailInfo = this.getSendEmailInfo.bind(this);
    }

    @action
    setUrlParams(params={}){
        this.urlParams = params;
        if(this.urlParams.tabTitle){
            this.title = Base64.decode(decodeURIComponent(this.urlParams.tabTitle));
        }
    }

    appendBaseParams(params) {
        this.baseParams = {...this.baseParams,...params};
    }

    reLoad(params={}, retainChecked=true){
        let bool = true;
        let tabkeys = [];
        //全部Tab打开表单按需判断是否刷新列表
        if (this.urlParams && "tabkeys" in this.urlParams) {
            tabkeys = this.urlParams.tabkeys.split(",");
        }
        if (params.from === "openReq" && tabkeys.length <= 0 && parseInt(this.searchParams.viewcondition) === 0 && (params.needReloadList !== true || this.baseParams.viewScope === "mine"))
            bool = false;

        this.initDatas({}, bool);
        if(bool){
            if(this.baseParams.viewScope === "doing" && ((params.requestid && params.requestid != "") || (params.submitReqIds && params.submitReqIds != ""))){
                API_LIST.getHendledReqIds(params).then((data) => {
                    const hendledReqIds = data.hendledReqIds;//待办列表，并且走列表回刷时，获取来源requestid中已经不在待办的requestid，满足走微搜条件时传给微搜处理
                    this.doSearch({hendledReqIds:hendledReqIds}, true, retainChecked);
                });
            }else{
                this.doSearch({}, true, retainChecked);
            }
        }
    }

    initDatas(params = {}, needLoadBase=true) {
        if (needLoadBase)
            this.loadBaseInfo(params);
        this.loadCountInfo(params);
    }

    loadBaseInfo(params = {}){
        API_LIST.getWfRequestList({ ...this.baseParams, ...this.urlParams, actiontype: "baseinfo" }).then((data) => {
            const { countcfg, groupinfo = [], pagetitle, treedata, conditioninfo } = data;
            WeaTools.ls.set(`list${this.baseParams.viewScope}LeftTree`, treedata);
            if(!this.title){
                this.title = pagetitle;
            }
            if(this.baseParams.viewScope != "doing"){
                this.topTab = groupinfo;
                this.topTabTemp = groupinfo;
            }
            this.leftTreeCountType = countcfg;
            this.leftTree = treedata;
            this.condition = conditioninfo;
            /*if (groupinfo.length > 0 && this.urlParams && "tabkeys" in this.urlParams && this.nowViewType !== 0 && this.nowViewType !== 1) {//已点过反馈和未读，不更新viewcondition
                groupinfo.map(item => {
                    if (this.baseParams.viewScope === "mine") {
                        if (item.viewcondition == 16) {
                            this.searchParams.viewcondition = "16"
                        }
                    } else if (this.baseParams.viewScope === "done") {
                        if (item.viewcondition == 10) {
                            this.searchParams.viewcondition = "10"
                        }
                    }
                })
            }*/
            //根据高级搜索条件初始化form
            this.form && !this.form.isFormInit && this.form.initFormFields(conditioninfo);
        });
    }

    loadCountInfo(params = {}){
        this.searchParams = { ...this.searchParams, ...params };
        const method = this.searchParams.method;
        API_LIST.getWfRequestList({ ...this.baseParams, ...this.urlParams, actiontype: "countinfo" }).then((data) => {
            this.leftTreeCount = data.treecount;

            let topCount = {};
            if(method === "reqeustbytype" || method === "reqeustbywfid"){
                if(this.selectedTreeKey in data.treecount){
                    topCount = data.treecount[this.selectedTreeKey];
                }else{
                    this.topTab && this.topTab.map(v =>{
                        topCount[v.groupid] = "0";
                    });
                }
            }else{
                topCount = data.totalcount;
            }
            this.topTabCount = topCount;

            if(this.baseParams.viewScope === "doing"){//待办接口改为toptab由doing接口返回
                this.baseParams.hideNoDataTab = data.hideNoDataTab;
                this.topTabTemp = data.topTab;
                /*if (this.topTabTemp.length > 0 && this.urlParams && "tabkeys" in this.urlParams) {
                    this.topTabTemp.map(item => {
                        if (this.baseParams.viewScope === "mine") {
                            if (item.viewcondition == 16) {
                                this.searchParams.viewcondition = "16"
                            }
                        } else if (this.baseParams.viewScope === "done") {
                            if (item.viewcondition == 10) {
                                this.searchParams.viewcondition = "10"
                            }
                        }
                    })
                }*/
                this.removeNoDataTab();
            }
        });
    }

    //待办全部数据下隐藏无数据tab
    removeNoDataTab = () => {
        let topTab_tmp = [...this.topTabTemp];
        if (this.baseParams.viewScope === "doing" && this.baseParams.hideNoDataTab === true) {//待办中隐藏掉无数据tab
            for (let item in this.topTabCount) {
                topTab_tmp = topTab_tmp.filter(tab=>!((tab.groupid === item && this.topTabCount[item] === "0" && tab.viewcondition != this.searchParams.viewcondition) || (!this.topTabCount[tab.groupid])))
            }
        }
        this.topTab = topTab_tmp;
    }

    doSearch(params = {}, retainSort=false, retainChecked=false) {
        const isDoing = this.baseParams.viewScope === "doing" && this.operBtnKey === 'batchSubmit';

        //获取表单的参数值
        const searchParamsAd = this.form.getFormParams();
        const newParams = { ...this.baseParams, ...this.searchParams, ...searchParamsAd, ...this.urlParams, ...params, actiontype: "splitpage" };

        const workflowidtmp = (searchParamsAd.workflowid && searchParamsAd.workflowid != "") ? searchParamsAd.workflowid : (((this.urlParams && this.urlParams.workflowid) ? this.urlParams.workflowid : ""));
        if(newParams.workflowid){
            newParams.workflowid = workflowidtmp;
        }
        const workflowtypetmp = (searchParamsAd.workflowtype && searchParamsAd.workflowtype != "") ? searchParamsAd.workflowtype : (((this.urlParams && this.urlParams.workflowtype) ? this.urlParams.workflowtype : ""));
        if(newParams.workflowtype){
            newParams.workflowtype = workflowtypetmp;
        }

        this.loading = true;
        if(newParams.method === "reqeustbytype" || newParams.method === "reqeustbywfid")
            this.topTabCount = this.leftTreeCount[this.selectedTreeKey];

        let current = 1;
        let sortParams = [];
        let selectedRowKeys = [];
        if(this.tableStore){    //页码、排序、选中状态需保留
            if(retainSort){
                current = this.tableStore.current || 1;
                sortParams = this.tableStore.sortParams.toJS() || [];
            }
            if(retainChecked && isDoing){
                selectedRowKeys = mobx.toJS(this.tableStore.selectedRowKeys) || [];
            }
        }


        this.searchParams = { ...this.searchParams, ...params };
        delete this.searchParams.viewtype;
        delete this.searchParams.hendledReqIds;
        delete this.searchParams.loadDefTab;
        if(this.baseParams.viewScope === "doing"){
            this.removeNoDataTab();
        }

        API_LIST.getWfListParams(newParams).then((data) => {
            if(data.viewcondition && data.viewcondition != ''){
                newParams.viewcondition = data.viewcondition;
                this.searchParams.viewcondition = data.viewcondition;
                this.searchParams.defaultTabVal = data.viewcondition;
            }
            API_LIST.getWfRequestList(newParams).then((data) => {
            window.continuationProcessQueryParams = newParams;
                if(data.fromQuickSearch === true){
                    this.quickSearchParams = data.reqParamsMap;
                    this.fromQuickSearch = true;
                }else{
                    this.quickSearchParams = {};
                    this.fromQuickSearch = false;
                }
                this.tableStore.getDatas(data.sessionkey, current, "", sortParams, ()=>{
                    if(retainChecked && isDoing && selectedRowKeys.length > 0){   //重置刷新前的选中状态
                        let newKeys = {};
                        this.tableStore.datas.map(row=>{
                            newKeys[`${row.requestid}_${row.userid}`] = true;
                        });
                        selectedRowKeys = selectedRowKeys.filter(v=>v in newKeys);
                        this.tableStore.setNotUniqueSelectedRowKeys(selectedRowKeys);   //唯一key才调用此方法
                    }
                    if(isDoing && !_.isEmpty(this.leftTreeCount))
                        this.judgeReloadCount(newParams);
                });
                this.sharearg = data.sharearg;
                this.loading = false;   //最后一次修改观察模式的状态，减少render次数
                if (params.viewtype == 0 && !_.some(this.topTab, { groupid: "flowNew" })) {//当前点击过红色
                    switch (this.baseParams.viewScope) {
                        case "mine": this.searchParams.viewcondition = "16"; break;
                        case "done": this.searchParams.viewcondition = "10"; break;
                    }
                } else if (params.viewtype == 1 && !_.some(this.topTab, { groupid: "flowRes" })) {//当前点击过黄色
                    switch (this.baseParams.viewScope) {
                        case "mine": this.searchParams.viewcondition = "16"; break;
                        case "done": this.searchParams.viewcondition = "10"; break;
                    }
                }
            });
        });
    }

    //判断顶部数字与列表数据的条数是否一致，不一致则请求一次取数接口(直接copy链接提交表单无法刷新待办情况)
    judgeReloadCount(params={}){
        const viewcondition = params.viewcondition;
        if(viewcondition == 0 && this.selectedTreeKey === "")
            return;     //加载全部情况不判断
        let groupkey = "";
        this.topTab && this.topTab.map(item =>{
            if(item.viewcondition == viewcondition)
                groupkey = item.groupid;
        });
        const listcount = parseInt(this.tableStore.count);
        let topcount = 0;
        if(this.topTabCount && groupkey !== "")
            topcount = parseInt(this.topTabCount[groupkey])
        if(topcount !== listcount)
            this.loadCountInfo();
    }

    setConditionByTree(){
        const key = this.selectedTreeKey;
        if(!key)
            return;
        //选中树节点同步修改高级查询条件
        let formFields = {};
        if(key.indexOf("wf_") === 0){
            const workflowid = key.substring(3);
            let workflowname = '';
            this.leftTree && this.leftTree.map(t =>{
                t.childs && t.childs.map(w =>{
                    if(w.domid === key)
                        workflowname = w.name;
                });
            });
            formFields["workflowid"] = {value:workflowid, valueSpan:workflowname};
        }else if(key.indexOf("type_") === 0){
            const workflowtype = key.substring(5);
            let typename = '';
            this.leftTree && this.leftTree.map(t =>{
                if(t.domid === key)
                    typename = t.name;
            });
            formFields["workflowtype"] = {value:workflowtype, valueSpan:typename};
        }
        this.setFormFields(formFields);
    }

    clearStatus(){
        if(this.searchParams.defaultTabVal == -1){
            this.searchParams.viewcondition = 0;
        }else{
            this.searchParams.viewcondition = this.searchParams.defaultTabVal;
        }
        // 设置 默认标题
        const viewScope = this.baseParams.viewScope;
        if("doing" === viewScope){
            this.title = getLabel(1207,"待办事宜");
        }else if("mine" === viewScope){
            this.title = getLabel(1210,"我的请求");
        }else if("done" === viewScope){
            this.title = getLabel(17991,"已办事宜");
        }
        this.showSearchAd = false;
        this.selectedTreeKey = "";
        this.clearFormFields();
        this.resetForm();
        this.condition = [];
        this.resetTable(true);
        this.nowViewType = 2;
    }

    setNowViewType = (v) => {
        this.nowViewType = v;
    }


    clickButttonDrop(key){
        this.tableStore.tableUpdate({checkId:key, selectedRowKeys:[]});
        this.tableStore.reloadCurrent(()=>{
            this.btnObj = {key:key, disabled:true};
            this.operBtnKey = key;
        });
    }

    setSingleRequestid(value) {
        this._singleRequestid = value;
    }

    getSingleRequestid(){
        return this._singleRequestid;
    }

    @action
    setShowBatchSupervisor(bool = false,requestid = '') {
        this.setSingleRequestid(requestid);
        this.showBatchSupervisor = bool;
    }

    @action
    setShowBatchSupervisorEmail(bool = false,requestid = '') {
        this.setSingleRequestid(requestid);
        this.showBatchSupervisor = bool;
    }

    @action
    setShowBatchSupervisorSms(bool = false,requestid = '') {
        this.setSingleRequestid(requestid);
        this.showBatchSupervisor = bool;
    }

    @action('流程督办')
    doSupervise(params = {}){
        message.loading(getLabel(387110,'督办中...，请稍候'),0);
        API_SUPERVISE.doSupervise(params).then((data)=>{
            message.destroy();
            if(data.result){
                this.handleParams = {};
                message.success(getLabel(387108,'督办成功'));
                this.reLoad();
            }else{
                message.error(getLabel(387109,'督办失败'));
            }
        });
    }


    @action('新建短信关闭打开')
    setSmsVisible(smsVisible = false){
        this.smsVisible = smsVisible;
        this.smsVisible_mount = smsVisible
    }

    @action('新建短信参数设置')
    setSmsParams(smsParams={}){
        this.smsParams = {...this.smsParams,...smsParams};
    }

    @action('发送邮件显隐')
    setEmailVisible(emailVisible = false){
        this.emailVisible = emailVisible;
        this.emailVisible_mount = emailVisible;
    }


    @action('获取邮件催件信息')
    getSendEmailInfo(params={}){
        API_SUPERVISE.getSendEmailInfo(params).then((data)=>{
            this.fwquery = data.fwquery || {};
            if(data.result){
                this.setEmailVisible(true);
            }
        });
    }

}